package jenetics.test;

import java.util.stream.Stream;

import org.jenetics.BitChromosome;
import org.jenetics.BitGene;
import org.jenetics.Mutator;
import org.jenetics.Phenotype;
import org.jenetics.RouletteWheelSelector;
import org.jenetics.SinglePointCrossover;
import org.jenetics.TournamentSelector;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionStatistics;

import static org.jenetics.engine.limit.bySteadyFitness;
import static org.jenetics.engine.EvolutionResult.toBestPhenotype;

public class Knapsack {

	public static void main(String[] args) {
		
		final int nitems = 15;
		final double kssize = nitems * 100.0 / 3.0;
		
		final FF ff = new FF(Stream.generate(Item::random).limit(nitems).toArray(Item[]::new), kssize);
		
		final Engine<BitGene, Double> engine = 
				Engine.builder(ff, BitChromosome.of(nitems, 0.5)).populationSize(500).survivorsSelector(new TournamentSelector<>(5)).offspringSelector(new RouletteWheelSelector<>())
				.alterers(new Mutator<>(0.115), new SinglePointCrossover<>(0.16)).build();
		
		final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();
		
		final Phenotype<BitGene, Double> best = engine.stream().limit(bySteadyFitness(7)).limit(100).peek(statistics).collect(toBestPhenotype());
		
		System.out.println(statistics);
		System.out.println(best);
	}

}